<template>
  <div class="role-container">
    <el-card class="operation-card">
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增角色
        </el-button>
        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </div>
    </el-card>

    <el-card class="table-card">
      <vxe-table
        v-model:data="tableData"
        :loading="loading"
        @checkbox-change="handleSelectionChange"
        @checkbox-all="handleSelectionChange"
      >
        <vxe-column type="checkbox" width="60" />
        <vxe-column field="id" title="ID" width="80" />
        <vxe-column field="name" title="角色名称" width="150" />
        <vxe-column field="code" title="角色编码" width="150" />
        <vxe-column field="sort" title="排序" width="80" />
        <vxe-column field="status" title="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'danger'">
              {{ row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </vxe-column>
        <vxe-column field="createTime" title="创建时间" width="180" />
        <vxe-column field="remark" title="备注" min-width="150" />
        <vxe-column title="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button type="success" link @click="handlePermission(row)">
              <el-icon><Key /></el-icon> 权限
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <vxe-pager
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 30, 50]"
        @page-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      v-model="dialogVisible"
      width="500px"
         :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
      destroy-on-close
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
        style="max-width: 460px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="roleForm.sort" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="roleForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
      title="分配权限"
      v-model="permissionDialogVisible"
      width="600px"
         :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
      destroy-on-close
    >
      <el-form>
        <el-form-item label="角色名称">
          <span>{{ currentRole.name }}</span>
        </el-form-item>
        <el-form-item label="权限分配">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedKeys"
            :props="{ label: 'name', children: 'children' }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermission">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Plus,
  Edit,
  Delete,
  Key
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义组件名
defineOptions({
  name: 'RoleListPage'
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const roleFormRef = ref(null)
const roleForm = reactive({
  id: '',
  name: '',
  code: '',
  sort: 0,
  status: '1',
  remark: ''
})

// 权限对话框
const permissionDialogVisible = ref(false)
const permissionTreeRef = ref(null)
const permissionTree = ref([])
const checkedKeys = ref([])
const currentRole = ref({})

// 表单校验规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 获取角色列表
const getRoleList = () => {
  loading.value = true
  // 实际项目中这里会调用后端API
  setTimeout(() => {
    // 模拟数据
    const mockRoles = [
      { id: 1, name: '超级管理员', code: 'ADMIN', sort: 1, status: '1', createTime: '2023-10-01 12:00:00', remark: '系统超级管理员，拥有所有权限' },
      { id: 2, name: '普通用户', code: 'USER', sort: 2, status: '1', createTime: '2023-10-01 12:00:00', remark: '普通用户，拥有基本操作权限' },
      { id: 3, name: '访客', code: 'GUEST', sort: 3, status: '1', createTime: '2023-10-01 12:00:00', remark: '访客，只有查看权限' },
      { id: 4, name: '运营专员', code: 'OPERATION', sort: 4, status: '1', createTime: '2023-10-01 12:00:00', remark: '负责内容运营和管理' },
      { id: 5, name: '财务人员', code: 'FINANCE', sort: 5, status: '1', createTime: '2023-10-01 12:00:00', remark: '负责财务相关操作' },
      { id: 6, name: '测试账号', code: 'TEST', sort: 6, status: '0', createTime: '2023-10-01 12:00:00', remark: '仅用于测试' }
    ]

    tableData.value = mockRoles
    pagination.total = mockRoles.length
    loading.value = false
  }, 500)
}

// 初始化权限树
const initPermissionTree = () => {
  // 实际项目中这里会调用后端API获取权限菜单树
  permissionTree.value = [
    {
      id: '1',
      name: '系统管理',
      children: [
        { id: '11', name: '用户管理' },
        { id: '12', name: '角色管理' },
        { id: '13', name: '菜单管理' },
        { id: '14', name: '部门管理' }
      ]
    },
    {
      id: '2',
      name: '内容管理',
      children: [
        { id: '21', name: '文章管理' },
        { id: '22', name: '分类管理' },
        { id: '23', name: '标签管理' },
        { id: '24', name: '评论管理' }
      ]
    },
    {
      id: '3',
      name: '系统监控',
      children: [
        { id: '31', name: '在线用户' },
        { id: '32', name: '操作日志' },
        { id: '33', name: '登录日志' },
        { id: '34', name: '服务监控' }
      ]
    }
  ]
}

// 初始化数据
onMounted(() => {
  getRoleList()
  initPermissionTree()
})

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  getRoleList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getRoleList()
}

// 新增角色
const handleAdd = () => {
  dialogType.value = 'add'
  roleForm.id = ''
  roleForm.name = ''
  roleForm.code = ''
  roleForm.sort = 0
  roleForm.status = '1'
  roleForm.remark = ''
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogType.value = 'edit'
  roleForm.id = row.id
  roleForm.name = row.name
  roleForm.code = row.code
  roleForm.sort = row.sort
  roleForm.status = row.status
  roleForm.remark = row.remark
  dialogVisible.value = true
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除角色【${row.name}】吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际项目中这里会调用删除API
    ElMessage.success('删除成功')
    getRoleList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}条记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际项目中这里会调用批量删除API
    ElMessage.success('批量删除成功')
    getRoleList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 设置权限
const handlePermission = (row) => {
  currentRole.value = row
  permissionDialogVisible.value = true

  // 实际项目中这里会调用API获取当前角色的权限
  // 这里模拟不同角色拥有不同的权限
  if (row.id === 1) {
    // 超级管理员拥有所有权限
    checkedKeys.value = ['11', '12', '13', '14', '21', '22', '23', '24', '31', '32', '33', '34']
  } else if (row.id === 2) {
    // 普通用户拥有部分权限
    checkedKeys.value = ['11', '21', '22', '23', '31']
  } else if (row.id === 3) {
    // 访客只有少量查看权限
    checkedKeys.value = ['11', '21']
  } else {
    // 其他角色默认
    checkedKeys.value = []
  }
}

// 保存权限设置
const savePermission = () => {
  const checkedNodes = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedNodes = permissionTreeRef.value.getHalfCheckedKeys()
  const permissionIds = [...checkedNodes, ...halfCheckedNodes]

  // 实际项目中这里会调用保存权限的API
  console.log('保存权限IDs:', permissionIds)

  ElMessage.success('权限分配成功')
  permissionDialogVisible.value = false
}

// 提交表单
const submitForm = async () => {
  try {
    await roleFormRef.value.validate()

    // 实际项目中这里会调用添加/更新API
    ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
    dialogVisible.value = false
    getRoleList()
  } catch (error) {
    console.error('表单验证失败', error)
  }
}
</script>

<style scoped>
.role-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
  box-sizing: border-box;
}

.operation-card {
  margin-bottom: 20px;
  width: 100%;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.table-card {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.vxe-table) {
  flex: 1;
  background-color: var(--el-bg-color);
}

:deep(.vxe-table--header-wrapper) {
  background-color: var(--el-fill-color-light);
}

:deep(.vxe-table--body-wrapper) {
  background-color: var(--el-bg-color);
}

:deep(.vxe-pager) {
  margin-top: 16px;
  padding: 0;
  justify-content: flex-end;
  background-color: transparent;
}

:deep(.vxe-table--render-default .vxe-body--column) {
  padding: 8px;
}

:deep(.vxe-table--render-default .vxe-header--column) {
  padding: 8px;
  font-weight: bold;
}
</style>
